//
//  AFNetManager+wxPay.m
//  TestJSPay
//
//  Created by hongliang on 16/3/26.
//  Copyright © 2016年 hongliang. All rights reserved.
//

#import "AFNetManager+wxPay.h"
#import "HLBaseData.h"
#import "WXPayData.h"

@implementation AFNetManager (wxPay)
- (NSURLSessionDataTask*)wxPayWithDianKaiOrderId:(NSString*)orderIdDianKai paymentAmount:(NSString*)paymentAmount finished:(HttpRequestFinishedBlock)finishBlock {
    NSDictionary* dictParams = @{@"payType":@"wxpay",
                                 @"diankaiOrderId":orderIdDianKai,
                                 @"price":paymentAmount,
                                 @"productNum":@"1"};
    return [self.afHTTPSessionManager POST:@"pay/createOrder" parameters:dictParams success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        WXPayData* payData = [WXPayData parseObjectFormJsonObject:responseObject];
        if (payData) {
            if (finishBlock) {
                finishBlock(@{HTTPResDataKey:payData}, nil);
            }
        }else {
            if (finishBlock) {
                finishBlock(nil, [NSError errorWithDomain:HTTPErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"pay/create api fail"}]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (finishBlock) {
            finishBlock(nil, error);
        }
    }];
}

#pragma mark - 查询订单状态
- (BOOL)didStartQueryPay:(NSString*)tradeNo finished:(HttpRequestFinishedBlock)finishBlock {
    return [self didFirstRetryQueryPay:tradeNo finished:finishBlock];
}

- (BOOL)isQueryPaySuccess:(NSDictionary*)dictResult {
    return ([[WXPayData payOrderStaus:dictResult] isEqualToString:@"1003"]);
}

- (BOOL)didFirstRetryQueryPay:(NSString *)tradeNo finished:(HttpRequestFinishedBlock)finishBlock {
    return [self didRetryQueryPay:tradeNo afterSeconds:2 finished:^(NSDictionary *dictResult, NSError *error) {
        if (!error && [self isQueryPaySuccess:dictResult]) {
            if (finishBlock) {
                finishBlock(dictResult, error);
            }
        }else {
            [self didSecondRetryQueryPay:tradeNo finished:finishBlock];
        }
    }];
}

- (BOOL)didSecondRetryQueryPay:(NSString *)tradeNo finished:(HttpRequestFinishedBlock)finishBlock {
    return [self didRetryQueryPay:tradeNo afterSeconds:4 finished:^(NSDictionary *dictResult, NSError *error) {
        if (!error && [self isQueryPaySuccess:dictResult]) {
            if (finishBlock) {
                finishBlock(dictResult, error);
            }
        }else {
            [self didThirdRetryQueryPay:tradeNo finished:finishBlock];
        }
    }];
}

- (BOOL)didThirdRetryQueryPay:(NSString *)tradeNo finished:(HttpRequestFinishedBlock)finishBlock {
    return [self didRetryQueryPay:tradeNo afterSeconds:8 finished:^(NSDictionary *dictResult, NSError *error) {
        if (!error) {
            if ([self isQueryPaySuccess:dictResult]) {
                if (finishBlock) {
                    finishBlock(dictResult, error);
                }
            }else {
                if (finishBlock) {
                    finishBlock(dictResult, [NSError errorWithDomain:@"jjk.parseQueryPay" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"支付失败"}]);
                }
            }
        }else {
            if (finishBlock) {
                finishBlock(dictResult, error);
            }
        }
    }];
}

- (BOOL)didRetryQueryPay:(NSString *)tradeNo afterSeconds:(NSInteger)seconds finished:(HttpRequestFinishedBlock)finishBlock {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self didQueryPay:tradeNo finished:^(NSDictionary *dictResult, NSError *error) {
            if (finishBlock) {
                finishBlock(dictResult, error);
            }
        }];
    });
    
    return YES;
}

- (NSURLSessionDataTask*)didQueryPay:(NSString*)tradeNo finished:(HttpRequestFinishedBlock)finishBlock {
    if (tradeNo.length <= 0) {
        return nil;
    }
    
    return [self.afHTTPSessionManager GET:@"pay/queryorder" parameters:@{@"orderId":tradeNo} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (finishBlock) {
            finishBlock(responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (finishBlock) {
            finishBlock(nil, error);
        }
    }];
}
@end
